package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.goods.TbGoods;
import com.dongdongshop.pojo.goods.TbGoodsDesc;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.pojo.item.TbItemCat;
import com.dongdongshop.service.*;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ItemPageServiceImpl implements ItemPageServiceI {
    //注入freemarker八大不
    @Autowired //前三步已经写了配置类了
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${freemarker.outPath}")
    private String outPath;

    @Reference
    private GoodsServiceI goodsServiceI;
    @Reference
    private GoodsDescServiceI goodsDescServiceI;
    @Reference
    private ItemServiceI itemServiceI;
    @Reference
    private ItemCatServiceI itemCatServiceI;
    @Override
    public void showItemPage(Long goodsId) {
        //创建模板 1.加载配置类
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        FileWriter fileWriter=null;
        try {
            //创建模板
            Template template = configuration.getTemplate("item.ftl");
            //创建模板数据
            Map map=new HashMap();
           //查询goods信息
           TbGoods goods = goodsServiceI.getGoodsId(goodsId);
           //查询goodsDesc对象
           TbGoodsDesc goodsDesc=goodsDescServiceI.getGoodsId(goodsId);
           //查询itemList
            List<TbItem> itemList=itemServiceI.selectItemByGoodsId(goodsId);
            //生成标题
            Long category1Id = goods.getCategory1Id();
            Long category2Id = goods.getCategory2Id();
            Long category3Id = goods.getCategory3Id();
            //查询itemCat
            TbItemCat iteCat1 = itemCatServiceI.getItemById(category1Id);
            TbItemCat iteCat2 = itemCatServiceI.getItemById(category2Id);
            TbItemCat iteCat3 = itemCatServiceI.getItemById(category3Id);

            map.put("goods",goods);
            map.put("goodsDesc",goodsDesc);
            map.put("itemList",itemList);
            map.put("iteCat1",iteCat1);
            map.put("iteCat2",iteCat2);
            map.put("iteCat3",iteCat3);

            //创建输出流
            fileWriter=new FileWriter(outPath+goodsId+".html");
            //输出
            template.process(map,fileWriter);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                //关闭资源 写在这是防止写//输出后面 但输出报错 不能关闭
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
